package com.ruoyi.tools;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

//友盟token换信息
public class YouMengToken {
    public static CloseableHttpResponse getResponse(String token, String phone) throws Exception {
        String umAppkey = ""; //友盟appkey ios  需要区分是安卓还是IOS
//        String umAppkey = ""; //友盟appkey 安卓 需要区分是安卓还是IOS
        String appKey = "203915191";  //阿里key
        String appSecret = "rtopEPaS6LhU5pkmdpngfy6ToEIhwLJx"; //阿里secret
        //String token = "eyJjIjoiT2VxeUFHVDZYS1R3bXBJN3Z6SHNJK2JacUJjYk1IcjM3elNSSkhkU0ZQWGFwUDdYdDlwZFB4OGZoMGcwNlBkcU5zZGJFZGJkdlI0clxuMXA3VzRqMlJsSHBROEx0QUowQURobjFtOHlrSU1oTGxudDdvaTUzcjhyZGFoWXlmWkhzcTd3Zk9WY0s2SzhIMVQxaERiV1wvd2wzUmNcbisrNEkwMG1GZHJXQngwU0VTakdJcDBPTlFmRTg2TTVEQityNzJHVktCSHR0dkdETzFIYys2ZkJpMVRDc2pmb2htQzFXVXIrTE1HSDVcbjhDcWd2K0RtbGc3NGhNSTYwOTFjRzVTXC92XC9xN2NwMnVCVXdmTWlweU5iOXpyNTIweTZDSDRxamVoeVpoTkdZelhaN3JkVlZuS1dxUlxueHhURlQrTUZEYmlVYzkrUmxvOERyOE9hXC9jbXlRSk55eXB1bkw0NDJHMWZsekNPK0p6STVjMGF5ZEdLSnlGTkVaR2krUXdDMHJuY2lcbnJEYUpEaVlBUXpkME51eWJLb1NvQ3ViZE5TcUcyc2p5dmErUkFISmN6K0dFWFJBaVdQQytnekxweWs1ZWE5d2tZaGdlZk8ybE8wYUdcbkFwSFYzTEJzeldwbkZjanhhcG1raFhISlllSlM1RXQ3MVNwb1lFb09heVFYWDhaRFU4bERIYld3aW5oMGZLR3p6RE5CYjYzNVdUbVpcbmRZSTlQZmdmQ0FFczdhT09XNVZEN0FYcVpwK3hSQVQ2cjd2dFlFTTA4a2JBNkxXRTZldGM3ZUw4aFpqbWhjV3k0ZE9PVVp4V3pPVWZcbnliMEtHQkV4ZjdzPVxuIiwiayI6ImdscENSSjl3REpoS2xxNUdJR1FOZEZqOHhvTDMwUDg0WVhTa3QzZHd3ZHA3UVFoeG5nUXdaN25rYklOYTY5UXpZUWo0TnBUUk1WQmoxSHFYdjZFQ2I1V1wvVEJkU1dCeVJvbXkySEFybXhFc3BTSHUrUlJmemF1bVRIRG0wMDZcL2p3OXNYWklyUG5uYVJ5a2pnN3h1M2t5NVRidTJiQVlrek9Fb09TYTBCZGU4Yk9rSjY1bUJtMnFxSit1M0RVWCtOOUJKWW1NV1hvWmJ4N0JKZzlVeU0xRXlocjZMSkFUYURaNHV0N1BRcXNZdmF1eEM3RjBKYW0rRkd3ZUZXRjNoXC9Od2U2MXhQak9qa1wvSWl2TjFBSkpTRUhWd3ZMKzV6SnZKbE9PQUVlYzVYbVhrZXUrOXh3aW16TmFjTENYV3JLdTFkTWNyOElhYkhqM292TmFqUlpVbGc9PSIsIm8iOiJBbmRyb2lkIn0=";
        String url = "https://verify5.market.alicloudapi.com/api/v1/mobile/verify?appkey=" + umAppkey;
        HttpPost httpPost = new HttpPost(url);
        /**
         * body
         */
        JSONObject object = new JSONObject();
        object.put("token", token);
        object.put("phoneNumber",phone);
        StringEntity stringEntity = new StringEntity(object.toJSONString(), StandardCharsets.UTF_8);
        httpPost.setEntity(stringEntity);
        /**
         * header
         */
        //请求体类型
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
        //请求响应体类型，部分 API 可以根据指定的响应类型来返回对应数据格式，建议手动指定此请求头，如果不设置，部分 HTTP 客户端会设置默认值 */*，导致签名错误
        httpPost.setHeader("Accept", "application/json");
        // API 版本号，目前所有 API 仅支持版本号『1』，可以不设置此请求头，默认版本号为『1』。
        httpPost.setHeader("X-Ca-Version", "1");
        httpPost.setHeader("X-Ca-Stage", "RELEASE");
        //请求的 阿里云AppKey，通过云市场等渠道购买的 API 默认已经给 APP 授过权，阿里云所有云产品共用一套 AppKey 体系，删除 ApppKey 请谨慎，避免影响到其他已经开通服务的云产品。
        httpPost.setHeader("X-Ca-Key", appKey);
        //请求的时间戳，值为当前时间的毫秒数，也就是从1970年1月1日起至今的时间转换为毫秒，时间戳有效时间为15分钟。
        httpPost.setHeader("X-Ca-Timestamp", String.valueOf(System.currentTimeMillis()));
        //请求唯一标识，15分钟内 AppKey+API+Nonce 不能重复，与时间戳结合使用才能起到防重放作用
        httpPost.setHeader("X-Ca-Nonce", UUID.randomUUID().toString());
        httpPost.setHeader("Content-MD5", Base64.encodeBase64String(DigestUtils.md5(object.toJSONString())));
        //参与签名的自定义请求头，服务端将根据此配置读取请求头进行签名，此处设置不包含 Content-Type、Accept、Content-MD5、Date 请求头，这些请求头已经包含在了基础的签名结构中，详情参照请求签名说明文档。
        httpPost.setHeader("X-Ca-Signature-Headers", "X-Ca-Version,X-Ca-Stage,X-Ca-Key,X-Ca-Timestamp");
        /**
         * sign
         */
        String stringToSign = getSignString(httpPost);
        System.out.println(stringToSign);
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        byte[] keyBytes = appSecret.getBytes(StandardCharsets.UTF_8);
        hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
        String sign = new String(Base64.encodeBase64(hmacSha256.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))));
        httpPost.setHeader("X-Ca-Signature", sign);
        /**
         * execute
         */
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            CloseableHttpResponse response = httpclient.execute(httpPost);
            System.out.println(response);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String getSignString(HttpPost httpPost) {
        Header[] headers = httpPost.getAllHeaders();
        Map<String, String> map = new HashMap<>();
        for (Header header : headers) {
            map.put(header.getName(), header.getValue());
        }
        return httpPost.getMethod() + "\n" +
                map.get("Accept") + "\n" +
                map.get("Content-MD5") + "\n" +
                map.get("Content-Type") + "\n\n" +
                "X-Ca-Key:" + map.get("X-Ca-Key") + "\n" +
                "X-Ca-Stage:" + map.get("X-Ca-Stage") + "\n" +
                "X-Ca-Timestamp:" + map.get("X-Ca-Timestamp") + "\n" +
                "X-Ca-Version:" + map.get("X-Ca-Version") + "\n" +
                httpPost.getURI().getPath() + "?" + httpPost.getURI().getQuery();
    }


}